package org.lhw.kaixin001.server;

import java.net.HttpURLConnection;
import java.net.URL;
import java.net.MalformedURLException;
import java.util.logging.Logger;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.OutputStreamWriter;

import org.lhw.kaixin001.client.GreetingService;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements
		GreetingService {

	public final static String URL_LOGIN = "http://wap.kaixin001.com/home/";
	public final static String URL_REFERER = "http://wap.kaixin001.com/";
	public final static String URL_PREFIX_PARKING = "http://wap.kaixin001.com/parking/index.php?verify=";
	public final static String URL_PREFIX_HOUSE = "http://wap.kaixin001.com/house/index.php?verify=";
	public final static String URL_PREFIX_SLAVE = "http://wap.kaixin001.com/slave/index.php?verify=";
	
	// http://wap.kaixin001.com/house/garden/?uid=11111111&verify=11111111_11111111_1252767141_993656677704b45d900298adee899cd7_kx
	public final static String URL_PREFIX_HOUSE_GARDEN = "http://wap.kaixin001.com/house/garden/?uid=";
	public final static String URL_PREFIX_HOUSE_MID_VERIFY = "&verify=";
	public final static String URL_PREFIX_HOUSE_GARDEN_HAVEST = "http://wap.kaixin001.com/house/garden/havest.php?";
	public final static String URL_PREFIX_HOUSE_GARDEN_GETFRIENDMATURE = "http://wap.kaixin001.com/house/garden/getfriendmature.php?verify=";
	
	public final static String URL_PREFIX_HOUSE_RANCH = "http://wap.kaixin001.com/house/ranch/?uid=";
	
	public final static String URL_PREFIX_HOUSE_JOB = "http://wap.kaixin001.com/house/joblist.php?verify=";
	public final static String URL_PREFIX_HOUSE_JOB_DO = "http://wap.kaixin001.com/house/dojob.php";
	
	private static final Logger log = Logger.getLogger(GreetingServiceImpl.class.getName());
	
	private StringBuilder logBuilder = null;
	
	public String processAccount(String email, String password) {
		logBuilder = new StringBuilder();
		postToHome(email, password);
		
		String ret = logBuilder.toString();
		log.info("email:"+email+"\r\n"+ret);
		return ret;
	}
	
	private String findText(final String s, final String prefix, final String suffix, int fromIndex){
		int iPrefix = s.indexOf(prefix, fromIndex);
		if (iPrefix==-1) return null;
		int iBegin = iPrefix + prefix.length();
		int iSuffix = s.indexOf(suffix, iBegin);
		if (iSuffix==-1) return null;
		return s.substring(iBegin, iSuffix);
	}
	
	/**
	 * 登录开心网，获取姓名、组件链接
	 * @param email
	 * @param password
	 */
	private void postToHome(String email, String password){
        try {
            URL url = new URL(URL_LOGIN);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Referer", URL_REFERER);
            StringBuilder postData = new StringBuilder()
	            .append("email=").append(email.replaceAll("@", "%40"))
	            .append("&password=").append(password)
	            .append("&from=&login=+%E7%99%BB+%E5%BD%95+")
	            ;
            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
            writer.write(postData.toString());
            writer.close();
    
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                // OK
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
                StringBuilder resultBuilder = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                	resultBuilder.append(line);
                }
                reader.close();
            	String sResult = resultBuilder.toString();
            	
            	//姓名
            	String name = findText(sResult, "<div class=\"cont\">", "：", 0);
            	if (name == null) return;
            	logBuilder.append("名字：").append(name).append("\r\n");
            	
            	//组件链接的verify值
            	String verifyValue = findText(sResult, "/app/mylist.php?verify=", "\"", 0);
            	if (verifyValue == null) return;
            	logBuilder.append("URL中的verify值：").append(verifyValue).append("\r\n");
            	
            	//id
            	int idIndex = verifyValue.indexOf('_');
            	if (idIndex==-1) return;
            	int id = Integer.parseInt(verifyValue.substring(0,idIndex));
            	logBuilder.append("id：").append(id).append("\r\n");
            	
            	//朋友买卖
            	resultBuilder = getHttpContent(URL_PREFIX_SLAVE+verifyValue);
            	if (resultBuilder != null) logBuilder.append("访问朋友买卖，每天获得100元").append("\r\n");
            	
            	//争车位
            	resultBuilder = getHttpContent(URL_PREFIX_PARKING+verifyValue);
            	if (resultBuilder == null) return;
            	//TODO
            	
            	//买房子
            	processJob(verifyValue);
            	processMyGarden(id, verifyValue);
            	processFriendsGarden(verifyValue);
            	processMyRanch(id, verifyValue);
            	processFriendsRanch(verifyValue);
            	
            } else {
                // Server returned HTTP error code.
            }
        } catch (MalformedURLException e) {
            // ...
        } catch (IOException e) {
            // ...
        }
	}
	
	/**
	 * 访问链接，获取内容，并返回StringBuilder
	 * @param sURL
	 */
	private StringBuilder getHttpContent(String sURL){
        try {
            URL url = new URL(sURL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                // OK
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
                StringBuilder resultBuilder = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                	resultBuilder.append(line);
                }
                reader.close();
            	return resultBuilder;
            } else {
                // Server returned HTTP error code.
            }
        } catch (MalformedURLException e) {
            // ...
        } catch (IOException e) {
            // ...
        }
        return null;
	}
	
	/**
	 * post数据到链接，获取内容，并返回StringBuilder
	 * @param sURL
	 */
	private StringBuilder postHttpContent(String sURL, String postData, String urlReferer){
        try {
	        URL url = new URL(sURL);
	        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
	        connection.setDoOutput(true);
	        connection.setRequestMethod("POST");
	        connection.setRequestProperty("Referer", urlReferer);
	        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
	        writer.write(postData);
	        writer.close();
	
	        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
	            // OK
	            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
	            StringBuilder resultBuilder = new StringBuilder();
	            String line;
	            while ((line = reader.readLine()) != null) {
	            	resultBuilder.append(line);
	            }
	            reader.close();
	        	return resultBuilder;
            } else {
                // Server returned HTTP error code.
            }
        } catch (MalformedURLException e) {
            // ...
        } catch (IOException e) {
            // ...
        }
        return null;
	}
		
	/**
	 * 打工
	 * @param resultBuilder
	 * @param verifyValue
	 */
	private void processJob(String verifyValue){
		StringBuilder resultBuilder = getHttpContent(URL_PREFIX_HOUSE_JOB+verifyValue);
		String result = resultBuilder.toString();
		int jobIdPos = result.lastIndexOf("<option value=\"");
		String sMaxJobId = findText(result, "<option value=\"", "\"", jobIdPos);
		if (sMaxJobId == null) return;
		
		//prepare post 
		// petid=12&verify=11111_111111_121212829_e33f851c27b60165ac0e7b9156ba01e6_kx
        StringBuilder postData = new StringBuilder()
        .append("petid=").append(sMaxJobId)
        .append("&verify=").append(verifyValue)
        ;
        
        StringBuilder doJobResult = postHttpContent(URL_PREFIX_HOUSE_JOB_DO, postData.toString(), URL_PREFIX_HOUSE_JOB+verifyValue);
        if (doJobResult==null) return;
        String sDoJobResult = findText(doJobResult.toString(), "<div class=\"tips1\">", "<br/>", 0);
        logBuilder.append(sDoJobResult).append("\r\n");
	}

	/**
	 * 自己的菜地
	 * @param id
	 * @param verifyValue
	 */
	private void processMyGarden(int id, String verifyValue){
		harvest(URL_PREFIX_HOUSE_GARDEN+id+URL_PREFIX_HOUSE_MID_VERIFY+verifyValue);		
	}
	
	private void harvest(String url){
		StringBuilder resultBuilder = getHttpContent(url);
		if (resultBuilder!=null){
			String sGarden = resultBuilder.toString();
			//收获
			int indexUrl = sGarden.indexOf("garden/havest.php?");
			String havestUrl = null;
			while((havestUrl=findText(sGarden, "garden/havest.php?", "\"", indexUrl))!=null){
				indexUrl = sGarden.indexOf("garden/havest.php?", indexUrl)+1;
				havestUrl = URL_PREFIX_HOUSE_GARDEN_HAVEST+havestUrl;
				havestUrl = havestUrl.replaceAll("&amp;", "&");
				StringBuilder havestBuilder = getHttpContent(havestUrl);
				if (havestBuilder != null){
					String sHavest = havestBuilder.toString();
					String what = findText(sHavest, "你已经收获了", "</div>", 0);
					if (what != null){
						logBuilder.append("收获了"+what).append("\r\n");
					}
					else{
						what = findText(sHavest, "你已经成功偷到", "</div>", 0);
						if (what != null){
							logBuilder.append("偷到"+what).append("\r\n");
						}
					}
						
				}
			}
		}
	}
	
	/**
	 * 偷朋友的菜地 TODO
	 * @param id
	 * @param verifyValue
	 */
	private void processFriendsGarden(String verifyValue){
		StringBuilder resultBuilder = getHttpContent(URL_PREFIX_HOUSE_GARDEN_GETFRIENDMATURE+verifyValue);
		if (resultBuilder!=null){
			String sGarden = resultBuilder.toString();
			//朋友的菜地
			Integer indexUrl = sGarden.indexOf("查找");
			String friendUrl = null;
			while((friendUrl=findText(sGarden, "<div class=\"list\"><a href=\"/", "\">", indexUrl))!=null){
				indexUrl = sGarden.indexOf("<div class=\"list\"><a href=\"/", indexUrl)+50;
				friendUrl = URL_REFERER+friendUrl;
				friendUrl = friendUrl.replaceAll("&amp;", "&");
				
				//好友姓名
				String sName = findText(sGarden, ">", "</a>", indexUrl);
				if (sName.equals("花园动态")) break;
				logBuilder.append("偷").append(sName).append("菜地").append("\r\n");

				harvest(friendUrl);
			}
		}		
	}
	
	/**
	 * 自己的牧场 TODO
	 * @param id
	 * @param verifyValue
	 */
	private void processMyRanch(int id, String verifyValue){
		StringBuilder resultBuilder = getHttpContent(URL_PREFIX_HOUSE_RANCH+id+URL_PREFIX_HOUSE_MID_VERIFY+verifyValue);
	}
	
	/**
	 * 偷朋友的动物 TODO
	 * @param id
	 * @param verifyValue
	 */
	private void processFriendsRanch(String verifyValue){

	}
}
